import {
  put, all, takeLatest
} from 'redux-saga/effects'
import api from '@API'
import { GET_MED_RECORD } from '@ACTIONS/medRecord'
import { handlerMedRecord } from '@UTILS/patient'
import Navigate from '@NAVIGATION/navigateManager'
import { MedRecordStatus } from '@INTERFACES/MedRecord'
import { SURVEY_STATUS_ENUM } from '@CONSTANTS/survey'
import { SESSION_TYPE } from '@CONSTANTS/common'
import { RoundType } from '@CONSTANTS/medRecord';
import { PATIENT_FILE_TYPE } from '@CONSTANTS/patient';

const getMedRecord = function* getSessions(action) {
  try {
    const { payload = {}, params } = action
    const result = yield api.getOrStartMedRecord(payload)
    const { FieldArray, ...extraData } = result
    const res = handlerMedRecord(FieldArray || [], result.MedRecord?.Round)
    yield put({
      type: GET_MED_RECORD.SUCCESS,
      data: { ...extraData, MedRecordQuestion: res }
    })
    const isSubmit = [MedRecordStatus.Submitted, MedRecordStatus.SurveyDone].includes(result.MedRecord.Status)
    if (isSubmit) {
      const surveys = result.MedRecord.Fields.Surveys
      const isMedFollowUp = result.MedRecord.Round !== RoundType.RegisterWithDoctor
      const first = surveys.find(item => item.SurveyStatus !== SURVEY_STATUS_ENUM.Submitted)
      const { patientId, doctorId, isFromChat, entityId } = params
      if (first) {
        Navigate.redirectTo('medRecordSurvey', { patientId, doctorId, isFromChat, entityId })
      } else {
        if (isFromChat) {
          Navigate.navigateBack()
          return
        }
        if (isMedFollowUp) {
          Navigate.redirectTo('patientDetail', { p8Id: patientId, type: PATIENT_FILE_TYPE.ElectMedRecord, mId: result.MedRecord.p8Id })
          return
        }
        const session = yield api.getActiveSessionByDocUserId({ dId: doctorId, pId: patientId, st: SESSION_TYPE.FollowUp })
        Navigate.redirectTo('chatRoomPage', {
          SessionId: session.p8Id,
        })
      }
    }
  } catch (error) {
    yield put({
      type: GET_MED_RECORD.FAILURE,
      error
    })
  }
}
export default function* rootSaga() {
  yield all([
    takeLatest(GET_MED_RECORD.REQUEST, getMedRecord),
  ])
}
